﻿// -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	SPWorkflowExts.cs
//  Developer:	Igor Solomatov
//  Created:	05.03.2013
// 
// -------------------- iSharePoint -------------------- //

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;

namespace Smart.Common
{
	public static class SPWorkflowExts
	{
		/// <summary>
		/// Find all active tasks
		/// </summary>
		public static List<SPWorkflowTask> FindActiveTasks(this SPWorkflowTaskCollection tasks)
		{
			return
				tasks
					.OfType<SPWorkflowTask>()
					.Where(
						task =>
						{
							if (task[SPBuiltInFieldId.Completed].SToBool(false))
								return false;

							var ato = task[SPBuiltInFieldId.AssignedTo].SToStr();

							return
								!ato.IsNullOrEmpty();
						})
					.ToList();
		}

		/// <summary>
		/// Find my task
		/// </summary>
		public static SPWorkflowTask FindMyTask(this SPWorkflowTaskCollection tasks)
		{
			return
				tasks
					.OfType<SPWorkflowTask>()
					.FirstOrDefault(
						task =>
						{
							if (task[SPBuiltInFieldId.Completed].SToBool(false))
								return false;

							var ato = task[SPBuiltInFieldId.AssignedTo].SToStr();

							if (ato.IsNullOrEmpty())
								return false;

							var atov = new SPFieldUserValue(task.Web, ato);

							return
								SPH.IsCurrentUserOrHisGroup(atov.LookupId);
						});
		}

		/// <summary>
		/// Find user task
		/// </summary>
		public static SPWorkflowTask FindUserTask(this SPWorkflowTaskCollection tasks, SPUser user)
		{
			return
				tasks
					.OfType<SPWorkflowTask>()
					.FirstOrDefault(
						task =>
						{
							if (task[SPBuiltInFieldId.Completed].SToBool(false))
								return false;

							var ato = task[SPBuiltInFieldId.AssignedTo].SToStr();

							if (ato.IsNullOrEmpty())
								return false;

							var atov = new SPFieldUserValue(task.Web, ato);

							return
								SPPrincipalExts.IsHimselfOrHisGroup(user, atov.LookupId);
						});
		}
	}
}